package com.pzhu.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pzhu.pojo.User;
import com.pzhu.service.LoginService;
import com.pzhu.service.impl.LoginServiceImpl;

public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式:
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//获取请求信息
		String uname=req.getParameter("uname");
		String pwd=req.getParameter("pwd");
		System.out.println(uname+":"+pwd);
		//处理请求信息
		//获取业务层对象
		LoginService ls=new LoginServiceImpl();
		User u=ls.checkLoginService(uname, pwd);
		System.out.println(u);
		//响应处理结果
		if(u!=null){
			//创建Cookie信息实现三天免登录。
			Cookie c=new Cookie("uid", u.getUid()+"");
			//设置Cookie的有效期
			c.setMaxAge(3*24*3600);
			c.setPath("/ln/ckl");
			//添加Cookie信息
			resp.addCookie(c);
			//请求转发
			//req.getRequestDispatcher("main").forward(req, resp);
			//将数据存储到session对象中
			HttpSession hs=req.getSession();
			hs.setAttribute("user",u);
			//创建网页计数器
			//获取计数数据
			ServletContext sc=this.getServletContext();
			if(sc.getAttribute("nums")!=null){
//						int nums=(int) sc.getAttribute("nums");
				int nums=Integer.parseInt(sc.getAttribute("nums")+"");
				//计数器自增
				nums+=1;
				//再次存储到ServletContext对象中
				sc.setAttribute("nums", nums);
			}else{
				sc.setAttribute("nums", 1);
			}

			//重定向
			resp.sendRedirect("/ln/main");
			return;
		}else{
			//使用request对象实现不同Servlet的数据流转
			req.setAttribute("str", "用户名或密码错误");
			//使用请求转发
			req.getRequestDispatcher("page").forward(req, resp);
			return;
		}
	}
}
